import 'package:dance_todo/data/bean_statistic.dart';
import 'package:dance_todo/db/bean_event.dart';
import 'package:dance_todo/db/bean_record.dart';
import 'package:dance_todo/main.dart';
import 'package:dance_todo/objectbox.g.dart';
import 'package:dance_todo/res/res_keys.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class StatisticCtrl extends GetxController {
  static StatisticCtrl get to => Get.find();

  final statistics = <StatisticBean>[].obs;

  @override
  void onInit() {
    super.onInit();
  }

  void analysisStatisticBeans() {
    var eventQuery = eventBox.query().build();
    List<Event> allEvents = eventQuery.find();

    var recordQuery = recordBox.query().build();
    List<Record> allRecords = recordQuery.find();

    List<StatisticBean> tempStatistics = [];
    for (var event in allEvents) {
      tempStatistics.add(
        new StatisticBean(
          name: event.name!,
          maxCount: 0,
          count: 0,
        ),
      );
    }

    int totalCount = 0;
    for (var statistic in tempStatistics) {
      var statisticName = statistic.name;
      for (var record in allRecords) {
        if (statisticName == record.name) {
          statistic.count += record.doneCount;
          if (statistic.count > totalCount) {
            totalCount = statistic.count;
          }
        }
      }
    }

    tempStatistics.forEach((statistic) {
      statistic.maxCount = totalCount;
    });

    tempStatistics.sort((o1, o2) {
      return o1.count.compareTo(o2.count);
    });

    statistics.value = tempStatistics;
    statistics.refresh();
  }
}
